#include "mystdio.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>


const char* toString(int flag)
{
  if(flag & NONE_FLUSH) return "NONE_FLUSH";
  else if(flag & LINE_FLUSH) return "LINE_FLUSH";
  else return "FULL_FLUSH";
}

void DebugPrint(myFILE* fp)
{
  printf("outbuffer:%s\n",fp->outbuffer);
  printf("fd:%d\n",fp->fileno);
  printf("pos:%d\n",fp->pos);
  printf("capacity:%d\n",fp->capacity);
  printf("flush_mode:%s\n",toString(fp->flush_mode));
}

myFILE* my_fopen(const char* pathname,const char* mode)
{
  int flag = 0;
  if(strcmp(mode,"r") == 0)
  {
    flag |= O_RDONLY;
  }
  else if(strcmp(mode,"w") == 0)
  {
    flag |= O_WRONLY|O_CREAT|O_TRUNC;
  }
  else if(strcmp(mode,"a") == 0)
  {
    flag |= O_WRONLY|O_CREAT|O_APPEND;
  }
  else
  {
    return NULL;
  }
  
  int fd = 0;
  if(flag & O_WRONLY)
  {
    fd = open(pathname,flag,0666);
    if(fd < 0) return NULL;
  }
  else
  {
    fd = open(pathname,flag);
    if(fd < 0) return NULL;
  }
  
  myFILE *fp = (myFILE*)malloc(sizeof(myFILE));
  if(fp == NULL) return NULL;
  fp->fileno = fd;
  fp->capacity = SIZE;
  fp->pos = 0;
  fp->flush_mode = LINE_FLUSH;//行刷新
  return fp;
}

void my_fflush(myFILE* fp)
{
  //缓冲区无数据，直接返回
  if(fp->pos == 0) return;
  write(fp->fileno,fp->outbuffer,fp->pos);
  fp->pos = 0;
}

int my_fwrite(myFILE* fp,const char* s, int size)
{
  //缓冲区
  //写入
  memcpy(fp->outbuffer + fp->pos,s,size);
  fp->pos += size;

  //判断刷新
  if(fp->flush_mode & LINE_FLUSH && fp->outbuffer[fp->pos-1] == '\n')
  {
      my_fflush(fp);
  }
  else if(fp->flush_mode & FULL_FLUSH && fp->pos == fp->capacity)
  {
      my_fflush(fp);
  }
  return size;
}
void my_fclose(myFILE* fp)
{
  //关闭文件之前刷新缓冲区
  my_fflush(fp);
  close(fp->fileno);
  free(fp);
  fp = NULL;
}
